<template>
  <div class="rf-select-item">
    <el-cascader :options="treeList" :props="defaultProps" style="width:200px" :show-all-levels="false"
                 @change="selectData" change-on-select v-model="defaultList" clearable :disabled="disabled"></el-cascader>
  </div>
</template>

<script>
  export default {
    name: 'cascaderSelectItem',
    props: {
      id: {
        type: [Number, String]
      },
      disabled: {
        type: Boolean,
        default: false
      },
      treeList: {
        type: Array,
        default: []
      }
    },
    data () {
      return {
        defaultList: [],
        defaultProps: {
          children: 'children',
          label: 'name',
          value: 'id'
        }
      }
    },
    watch: {
      id (newValue) {
        console.log(newValue)
        this.defaultList = this.getTreeDeepArr(newValue, this.treeList)
      }
    },
    methods: {
      selectData (data) {
        this.$emit('selectData', data[data.length - 1])
      },
      getTreeDeepArr (key, treeData) {
        let arr = [] // 在递归时操作的数组
        let returnArr = [] // 存放结果的数组
        let depth = 0 // 定义全局层级
        // 定义递归函数
        function childrenEach (childrenData, depthN) {
          for (var j = 0; j < childrenData.length; j++) {
            depth = depthN // 将执行的层级赋值 到 全局层级
            arr[depthN] = (childrenData[j].id)
            if (childrenData[j].id === key) {
              // returnArr = arr; // 原写法不行, 因 此赋值存在指针关系
              returnArr = arr.slice(0, depthN + 1) // 将目前匹配的数组，截断并保存到结果数组
              break
            } else {
              if (childrenData[j].children) {
                depth++
                childrenEach(childrenData[j].children, depth)
              }
            }
          }
          return returnArr
        }
        return childrenEach(treeData, depth)
      }
    }
  }
</script>

<style>
  .el-cascader-panel {
    display: flex;
    border-radius: 4px;
    font-size: 14px;
  }
  .el-cascader-menu {
    min-width: 180px;
    box-sizing: border-box;
    color: #606266;
    border-right: 1px solid #e4e7ed;
  }
  .el-scrollbar {
    overflow: hidden;
    position: relative;
  }
  .el-cascader-node {
    position: relative;
    display: flex;
    align-items: center;
    padding: 0 30px 0 20px;
    height: 34px;
    line-height: 34px;
    outline: none;
  }
  .el-scrollbar__view.el-cascader-menu__list{
    padding-left: 0;
  }
  .el-scrollbar__wrap{
    overflow: auto;
  }
  .el-cascader-node.in-active-path, .el-cascader-node.is-active, .el-cascader-node.is-selectable.in-checked-path {
    color: #409eff;
    font-weight: 700;
  }
</style>
